package com.rmfyzxfw.caseprocess.util;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @description:
 * @Author: GYW  742926306@qq.com
 * @Date: 2024/9/6 11:32
 */
public class TreeUtil {
    /**
     * 通用构造树的方法 递归实现
     * @param list 数据集
     * @param rootCheck 过滤根节点
     * @param parentCheck 判断父节点，前面参数为父节点 例如 (x, y) -> x.getFydmHy().equals(y.getSjfydmHy())
     * @param setSubChildren
     * @return
     * @param <E>
     */
    public static <E> List<E> makeTree(List<E> list, Predicate<E> rootCheck, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> setSubChildren) {
        return list.stream()
                .filter(rootCheck)
                .peek(x -> setSubChildren.accept(x, makeChildren(x, list, parentCheck, setSubChildren)))
                .collect(Collectors.toList());
    }
    private static <E> List<E> makeChildren(E parent, List<E> allData, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> setSubChildren) {
        return allData.stream()
                .filter(x -> parentCheck.apply(parent, x))
                .peek(x -> setSubChildren.accept(x, makeChildren(x, allData, parentCheck, setSubChildren)))
                .collect(Collectors.toList());
    }
}